package cn.wolfcode.trip.app.web.filter;


import cn.wolfcode.trip.app.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


//图片过滤器
//用于对图片的请求路径进行过滤
public class ImageFliter implements Filter{
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //对请求图片名字有/upload的请求进行拦截
        HttpServletRequest req = (HttpServletRequest)request;
        String image = req.getRequestURI();
        //System.out.println(image);  /upload/aae52cd5-d34f-4875-bc07-627544ed7090.jpg
        File file = new File(UploadUtil.IMG_PATH,image);
        //System.out.println(file);  e:/imgStore/upload/aae52cd5-d34f-4875-bc07-627544ed7090.jpg
        if(file.exists()){
            byte[] bytes = FileUtils.readFileToByteArray(file);
            response.getOutputStream().write(bytes);
        }else{
            chain.doFilter(request,response );
        }
    }

    public void destroy() {

    }
}
